export default (function () {
  let xhr = window.XMLHttpRequest
    ? new XMLHttpRequest()
    : new ActiveXObject("Microsoft.XMLHTTP");
  if (!xhr) {
    throw new error("IE4 不支持AJAX");
  }
  function _doAjax(options) {
    options = options || {};
    let type = (options.type || "GET").toUpperCase(),
      async = options.async || true,
      url = options.url,
      data = options.data || null,
      error = options.error || function () {},
      success = options.success || function () {},
      complete = options.complete || function () {};
    //complete 不论成果失败都会执行
    if (!url) {
      throw new Error("没写URL");
    }
    //短路运算
    //  || 第一个是false 直接返回第二个参数
    //  && 第一个是true 直接返回第二个参数
    xhr.open(type, url, async);
    type === "POST" &&
      xhr.setRequsetheader(
        "Content-type",
        "application/x-www-form-urlencodeed"
      );

    //处理post数据
    function formatDatas(data) {
      let str = "";
      for (let key in data) {
        str += "&" + key + "=" + data[key];
      }
      //去掉开头多余的 &
      return str.substr(1);
    }
    xhr.send(type === "GET" ? null : formatDatas(data));
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        success(xhr.responseText);
      }
      if (xhr.status === 404) {
        error();
      }
      complete();
    };
  }
  return {
    ajax: function (options) {
      _doAjax(options);
    },
    post: function (url, data, callback) {
      _doAjax({ type: "POST", url, data, success: callback });
    },
    get: function (url, callback) {
      _doAjax({ type: "GET", url, success: callback });
    },
  };
})();
